/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "plugins/ecmascript/runtime/ecma_compiler.h"
#include "plugins/ecmascript/runtime/compiler/ecmascript_runtime_interface.h"
#include "plugins/ecmascript/runtime/js_function.h"
#include "plugins/ecmascript/runtime/interpreter/js_frame.h"
#include "plugins/ecmascript/compiler/ecmascript_extensions/ecmascript_environment.h"
#include "plugins/ecmascript/runtime/global_handle_collection.h"
#include "plugins/ecmascript/runtime/ecma_global_storage-inl.h"
#include "plugins/ecmascript/compiler/ecmascript_extensions/thread_environment_api.h"
#include "runtime/mem/refstorage/global_object_storage.h"
#include "runtime/mem/refstorage/reference.h"

namespace ark::ecmascript {
void EcmaCompiler::AddTask(CompilerTask &&task, TaggedValue func)
{
    if (func.IsHole()) {
        if (auto stack = StackWalker::Create(GetJSThread()); !stack.IsCFrame()) {
            auto frame = stack.GetIFrame();
            if (frame != nullptr && !frame->GetMethod()->IsNative()) {
                auto currFunc = JSFunction::Cast(JSFrame::GetJSEnv(frame)->GetThisFunc());
                if (currFunc->GetMethod() == task.GetMethod()) {
                    func = TaggedValue(currFunc);
                }
            }
        }
    }
    if (func.IsHole()) {
        func = GetJSThread()->GetFunctionalObject();
    }
    if (!func.IsHole()) {
        ASSERT(JSFunction::Cast(func.GetHeapObject())->GetCallTarget() == task.GetMethod());
        auto gos = task.GetVM()->GetGlobalObjectStorage();
        auto funcRef = gos->Add(func.GetHeapObject(), ark::mem::Reference::ObjectType::GLOBAL);
        static_cast<EcmaRuntimeInterface *>(GetRuntimeInterface())->AddFunctionInMap(task.GetMethod(), funcRef);
    }
    Compiler::AddTask(std::move(task), func);
}

}  // namespace ark::ecmascript
